<template>
  <div class="container">
    <div class="header">
      <div class="left">
        <div class="line"></div>
        <h2>出差记录</h2>
        <el-input v-model="classSearchInput" placeholder="请输入姓名" style="width: 150px" class="className"
          v-if="roleId != '3' && roleId != '5'"></el-input>
        <el-date-picker v-model="currentYearMonth" type="month" placeholder="选择查询时间" style="width: 150px"
          value-format="YYYY-MM" class="className"></el-date-picker>
        <div style="position: relative">
          <el-button @click="handleSearch" class="search">搜索</el-button>
          <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
        </div>
      </div>
      <div class="right" v-if="roleId == '3' || roleId == '5'">
        <p @click="apply">申请</p>
        <el-dialog v-model="dialogVisible" :showClose="false">
          <header class="el-dialog__header">
            <h3>出差申请</h3>
          </header>
          <!-- 1. 为form-item添加prop，绑定验证规则 -->
          <el-form :model="formData" :rules="rules" ref="formRef" hide-required-asterisk>
            <el-row style="display: flex; justify-content: space-evenly; ">
              <el-form-item label="姓名" style="margin-left: 2em;" prop="teacherName">
                <el-input v-model="formData.teacherName" disabled></el-input>
              </el-form-item>
              <el-form-item label="开始时间" prop="beginTime">
                <el-date-picker v-model="formData.beginTime" type="date" placeholder="请选择开始时间" style="width: 200px;"
                  value-format="YYYY-MM-DD"></el-date-picker>
              </el-form-item>
            </el-row>
            <el-row style="display: flex; justify-content: space-evenly;">
              <el-form-item label="出差地点" prop="city">
                <el-input v-model="formData.city"></el-input>
              </el-form-item>
              <el-form-item label="返回时间" prop="returnTime">
                <el-date-picker v-model="formData.returnTime" type="date" placeholder="请选择返回时间" style="width: 200px;"
                  value-format="YYYY-MM-DD"></el-date-picker>
              </el-form-item>
            </el-row>
            <el-row style="margin-left: 60px;">
              <el-form-item label="交通工具" prop="vehicle">
                <el-input v-model="formData.vehicle"></el-input>
              </el-form-item>
            </el-row>
            <!-- 2. 新增总时长输入框（绑定num字段，用于验证和计算） -->
            <!-- <el-row style="margin-left: 60px; margin-top: 15px;">
              <el-form-item label="出差总时长(天)" prop="num">
                <el-input v-model="formData.num" placeholder="自动计算或手动输入"></el-input>
              </el-form-item>
            </el-row> -->
            <el-row class="footer" style="display: flex; justify-content: space-evenly;">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button @click="sure">确认</el-button>
            </el-row>
          </el-form>
        </el-dialog>
      </div>
    </div>
    <div class="content" style="border-radius: 20px !important;width: 90%;">
      <el-table :data="tableData" style="width: 100% ;margin: 0 auto;">
        <el-table-column prop="teacherName" label="姓名" align="center" />
        <el-table-column prop="city" label="出差地点" align="center" />
        <el-table-column prop="beginTime" label="出发时间" align="center" />
        <el-table-column prop="returnTime" label="返回时间" align="center" />
        <el-table-column prop="totalTime" label="出差总时长(天)" align="center" />
        <el-table-column prop="vehicle" label="交通工具" align="center" />
      </el-table>
     <div class="page" style="margin: 0 auto; width: 100%;display: flex;justify-content: center; background-color: #fff;">
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="currentPage"
          :page-size="pageSize" @current-change="handleCurrentPageChange" />
        <div>
          每页
          <el-input-number v-model="pageSize" :min="1" :max="30" controls-position="right" @change="handleChange" />条
        </div>

      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted } from 'vue'
import { getDay } from '../api/Daily'
import { getBusiness, getBusinessInfo, addBusiness } from '../api/Business'
import '@/assets/css/businesstripdiary.css'
import { reactive, ref } from 'vue'
import { ElDialog, ElButton, ElMessageBox, ElMessage } from 'element-plus';
const formRef = ref(null)
import dayjs from 'dayjs' // 引入 dayjs 库

// 定义当前年月
const currentYearMonth = ref('')
// 定义日期选择器的引用
const datePickerRef = ref(null)
//搜搜
const classSearchInput = ref('')
let dialogVisible = ref(false)
//获取身份（修复类型：转为字符串避免类型判断错误）
let roleId = sessionStorage.getItem('roleId') + ''
//当前页
let currentPage = ref(1)
//每个个数
let pageSize = ref(4)
//个数
let total = ref(0)
// 处理页码变化
const handleCurrentPageChange = (page) => {
  currentPage.value = page // 更新当前页码
  console.log(currentPage.value);

  if (roleId == '3' || roleId == '5') {
    fetchData2()
  } else {
    fetchData()
  }
}
function handleChange() {
  currentPage.value = 1; // 切换每页显示的数量时重置当前页码
  if (roleId == '3' || roleId == '5') {
    fetchData2()
  } else {
    fetchData()
  }
}
//数据
let tableData = ref([
  {
    teacherName: '',
    city: '',
    beginTime: '',
    returnTime: '',
    totalTime: '',
    vehicle: '',
    num: '',
  }
])
//申请数据
let formData = reactive(
  {
    teacherName: '',
    city: '',
    beginTime: '',
    returnTime: '',
    totalTime: '',
    vehicle: '',
    num: '',
  }
)
//管理员查看出差
function fetchData() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,

  }
  if (classSearchInput.value) {
    data.search = classSearchInput.value
  }
  if (currentYearMonth.value) {
    data.thisMonth = currentYearMonth.value
  }
  getBusiness("outsList", data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.outList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}
// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 切换年月时重置当前页码
  if (roleId == '3' || roleId == '5') {
    fetchData2()
  } else {
    fetchData()
  }
}

//调添加出差记录接口（修复totalTime计算方式）
function sure() {
  formRef.value.validate((valid) => {
    console.log(valid);
    if (valid) {
      ElMessageBox.confirm('是否提交？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        add()
        dialogVisible.value = false
        // 提交后重置表单
        formRef.value.resetFields()
      }).catch(() => {
        ElMessage.info('已取消')
      })
    }
  })

}
let add = async () => {
  // 3. 修复totalTime计算：用dayjs计算天数差，避免字符串相减错误
  const begin = dayjs(formData.beginTime)
  const returnT = dayjs(formData.returnTime)
  const totalDays = returnT.diff(begin, 'day') + 1 // 包含首尾天（如1号-2号算2天）
  
  let data = {
    teacherId: Number(sessionStorage.getItem('userId')),
    teacherName: formData.teacherName,
    city: formData.city,
    beginTime: formData.beginTime,
    returnTime: formData.returnTime,
    vehicle: formData.vehicle,
    totalTime: Number(formData.num) || totalDays // 优先用表单输入的num，次之自动计算
  }
  await addBusiness('addOut', data).then((res) => {
    console.log(res);
    if (res.code == 200) {
      ElMessage.success('添加成功')
      // 提交成功后重新拉取数据
      fetchData2()
    } else {
      ElMessage.error('添加失败：' + res.msg)
    }
  })
}
//点击申请
function apply() {
  dialogVisible.value = true
  // 打开弹窗时清空num字段，避免残留旧数据
  formData.num = ''
}
let userId = sessionStorage.getItem('userId')
//老师查看个人出差
function fetchData2() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    teacherId: Number(userId),
  }
  if (classSearchInput.value) {
    data.search = classSearchInput.value
  }
  if (currentYearMonth.value) {
    data.thisMonth = currentYearMonth.value
  }
  getBusinessInfo("outsList2", data).then(res => {
    if (res.code === 200) {
      tableData.value = res.dataset.outList2
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}
onMounted(() => {
  // 4. 修复姓名赋值：优先用userId对应的姓名，次之role
  formData.teacherName = sessionStorage.getItem('userName') || sessionStorage.getItem('role')
  if (roleId == '3' || roleId == '5') {
    fetchData2()
  } else {
    fetchData()
  }
})

// 开始时间必须在结束时间之前（修复字段名引用）
const validateStartTime = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择开始时间'))
    return
  }
  if (formData.returnTime && value) {
    const returnTime = dayjs(formData.returnTime)
    const beginTime = dayjs(value)
    if (returnTime.isBefore(beginTime)) {
      callback(new Error('开始时间必须在结束时间之前'))
    } else {
      // 自动计算总时长
      calculateNum()
      callback()
    }
  } else {
    callback()
  }
}

// 结束时间必须在开始时间之后（修复逻辑判断）
const validateEndTime = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择返回时间'))
    return
  }
  if (formData.beginTime && value) {
    const beginTime = dayjs(formData.beginTime)
    const returnTime = dayjs(value)
    if (returnTime.isBefore(beginTime)) {
      callback(new Error('结束时间必须在开始时间之后'))
    } else {
      // 自动计算总时长
      calculateNum()
      callback()
    }
  } else {
    callback()
  }
}

// 计算出差总时长（修复字段关联：num对应总时长）
const calculateNum = () => {
  if (formData.beginTime && formData.returnTime) {
    const beginTime = dayjs(formData.beginTime)
    const returnTime = dayjs(formData.returnTime)
    const days = returnTime.diff(beginTime, 'day') + 1 // 包含首尾天
    formData.num = days.toString()
  }
}

// 计算结束时间（修复字段名：beginTime替代startTime）
const calculateEndTime = () => {
  if (formData.beginTime && formData.num) {
    const beginTime = dayjs(formData.beginTime)
    const returnTime = beginTime.add(parseInt(formData.num), 'day')
    formData.returnTime = returnTime.format('YYYY-MM-DD')
  }
}

// 计算开始时间（修复字段名：returnTime替代endTime）
const calculateStartTime = () => {
  if (formData.returnTime && formData.num) {
    const returnTime = dayjs(formData.returnTime)
    const beginTime = returnTime.subtract(parseInt(formData.num), 'day')
    formData.beginTime = beginTime.format('YYYY-MM-DD')
  }
}

// 5. 修复验证规则：补充num字段的数值校验，确保总时长为正整数
const rules = ref({
  teacherName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  city: [{ required: true, message: '请输入出差地点', trigger: 'blur' }],
  beginTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    { validator: validateStartTime, trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.returnTime) {
          calculateNum()
        } else if (value && formData.num) {
          calculateEndTime()
        }
        callback()
      },
      trigger: 'change',
    },
  ],
  returnTime: [
    { required: true, message: '请选择返回时间', trigger: 'change' },
    { validator: validateEndTime, trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.beginTime) {
          calculateNum()
        } else if (value && formData.num) {
          calculateStartTime()
        }
        callback()
      },
      trigger: 'change',
    },
  ],
  vehicle: [{ required: true, message: '请输入交通工具', trigger: 'blur' }],
  num: [
    { required: true, message: '请输入出差总时长', trigger: 'blur' },
    { type: 'number', message: '总时长必须为数字', trigger: 'blur' },
    { min: 1, message: '总时长不能小于1天', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.beginTime && value) {
          calculateEndTime()
        } else if (formData.returnTime && value) {
          calculateStartTime()
        }
        callback()
      },
      trigger: 'blur',
    },
  ],
})
</script>
<style lang="less" scoped></style>